package com.atguigu.crowd.mvc.controller;

import com.atguigu.crowd.exception.AccessForbiddenException;
import com.atguigu.crowd.exception.LoginAcctDuplicateKeyException;
import com.atguigu.crowd.service.AdminService;
import com.atguigu.crowd.service.impl.AdminServiceImpl;
import com.atguigu.crowd.util.CrowdConstant;
import com.atguigu.crowd.util.ResultEntity;
import com.atguigu.entity.Admin;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.access.prepost.PreFilter;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Objects;

@Controller
public class AdminController {

    @Autowired
    private AdminService adminService;


    @RequestMapping("/admin/update")
    public String update(Admin admin,@RequestParam("pageNum") String pageNum,@RequestParam("keyWord") String keyWord){
        adminService.updateAdminById(admin);
        return "redirect:/admin/get/page?pageNum="+pageNum+"&keyWord="+keyWord;
    }

    @RequestMapping("/admin/to/edit/page/{id}")
    public String toEditPage(@PathVariable("id") Integer id,Model model){
        Admin admin = adminService.getAdminById(id);
        model.addAttribute("admin",admin);

        return "admin-edit";

    }

    @PreAuthorize("hasAuthority('user:save')")
    @RequestMapping("/admin/save")
    public String save(Admin admin){

        try {
            adminService.saveAdmin(admin);
        }catch (Exception e){
            e.printStackTrace();
            if(e instanceof DuplicateKeyException){
                throw new LoginAcctDuplicateKeyException(CrowdConstant.MESSAGE_LOGIN_ACCT_ALREADY_IN_USE);
            }
        }
        return "redirect:/admin/get/page?pageNum="+Integer.MAX_VALUE;
    }

    @ResponseBody
    @PreFilter(value = "filterObject%2==0")
    @RequestMapping("/admin/test/prefilter.json")
    public ResultEntity getAdmin(@RequestBody List<Integer> idsList){


        return ResultEntity.successResuleData(idsList);
    }

    @RequestMapping("/deleted/adminIds")
    @ResponseBody
    public ResultEntity deletedAdminIds(@RequestBody List<Integer> ids,HttpSession session){
        Admin admin = (Admin) session.getAttribute(CrowdConstant.ATTR_NAME_LOGIN_ADMIN);
        for (Integer id:
             ids) {
            if (Objects.equals(admin.getId(),id)){
                throw new RuntimeException(CrowdConstant.MESSAGE_ADMIN_DELETE_ERROR);
            }
            adminService.removeAdminById(id);
        }

        return ResultEntity.successData();
    }

    @RequestMapping("/deleted/admin")
    @ResponseBody
    public ResultEntity deletedAdmin(Integer id,HttpSession session){
        Admin admin = (Admin) session.getAttribute(CrowdConstant.ATTR_NAME_LOGIN_ADMIN);
        if (Objects.equals(admin.getId(),id)){
            throw new RuntimeException(CrowdConstant.MESSAGE_ADMIN_DELETE_ERROR);
        }
        adminService.removeAdminById(id);
        return ResultEntity.successData();
    }


    @RequestMapping("/admin/get/page")
    public String getPageInfo(
            @RequestParam(value = "keyWord",defaultValue = "") String keyWord,
            @RequestParam(value = "pageNum",defaultValue = "1") Integer pageNum,
            @RequestParam(value = "pageLimit",defaultValue = "5") Integer pageLimit,
            Model model

    ){


        PageInfo<Admin> pageInfo = adminService.getPageInfo(keyWord, pageNum, pageLimit);

        model.addAttribute(CrowdConstant.ATTR_NAME_PAGE_INFO,pageInfo);

        return "admin-page";
    }

    @RequestMapping("/admin/do/login")
    public String doLogin(
            @RequestParam("loginAcct") String loginAcct,
            @RequestParam("userPswd") String userPswd,
            HttpSession session
    ) {

        // 调用service登录检查
        Admin admin = adminService.getAdminByLoginAcct(loginAcct,userPswd);

        // 将登陆成功的返回对象存入session域
        session.setAttribute(CrowdConstant.ATTR_NAME_LOGIN_ADMIN,admin);
        return "redirect:/admin/to/main/page";
    }

    @RequestMapping("/admin/do/logout")
    public String doLogout(HttpSession session){

        session.invalidate();

        return "redirect:/admin/to/login/page.html";
    }
}
